package amdocs.jet.pm.safenote;

import java.util.ArrayList;
import java.util.Collections;

import org.restlet.engine.Engine;
import org.restlet.ext.net.HttpClientHelper;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;

import amdocs.jet.pm.Constants;
import amdocs.jet.pm.safenote.common.SafeNote;
import amdocs.jet.pm.safenote.common.SafeNoteResource;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable.Factory;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amdocs.jet.pm.R;
import com.googlecode.gwt.crypto.client.TripleDesCipher;

public class AddSafeNoteActivity extends Activity
{
	// screen controls
	private TextView textViewID;
	private EditText editTextName;
	private AutoCompleteTextView editTextCategory;
	private EditText editTextBody;
	private ArrayAdapter<String> autoCompleteTextViewAdapter;
	
	public ArrayList<String> categoryList = new ArrayList<String>();
	private SafeNote safeNote;
	private SafeNoteActionEnum safeNoteAction;
	
	private Menu optionMenu;
	
	// App Engine remote API
	public SafeNoteResource safeNoteResource;
	public ClientResource clientResource;
	
	public TripleDesCipher cipher = new TripleDesCipher();
	
    public void onCreate(Bundle icicle) 
    {
    	Engine.getInstance().getRegisteredClients().add(new HttpClientHelper(null)); 
        super.onCreate(icicle);       
        cipher.setKey(Constants.ENCRYPTION_KEY.getBytes());
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null)
        {
        	categoryList = bundle.getStringArrayList(Constants.KEY_CATEGORIES);
        	Collections.sort(categoryList, String.CASE_INSENSITIVE_ORDER);
        	safeNote = (SafeNote)bundle.getSerializable(Constants.KEY_SAFE_NOTE);
        	safeNoteAction = (SafeNoteActionEnum)bundle.getSerializable(Constants.KEY_ACTION);
        }
        setContentView(R.layout.add_safenote);
        initControls();
        if (SafeNoteActionEnum.EDIT.equals(safeNoteAction) || SafeNoteActionEnum.VIEW.equals(safeNoteAction))
        {
        	populateSafeNoteValues();
        }
        if (SafeNoteActionEnum.VIEW.equals(safeNoteAction))
        {
        	setControlsEnabling(false);
        }
        if (SafeNoteActionEnum.ADD.equals(safeNoteAction))
        {
        	if (safeNote != null)
        	{
        		editTextCategory.setText(safeNote.getSafeNoteCategoryName());
        	}
        }
    }
    
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.add_safenote_menu, menu);
		optionMenu = menu;
        if (SafeNoteActionEnum.ADD.equals(safeNoteAction))
        {
        	optionMenu.getItem(Constants.SAFE_NOTE_EDIT_MENU_ITEM_INDEX).setVisible(false);
        	optionMenu.getItem(Constants.SAFE_NOTE_DELETE_MENU_ITEM_INDEX).setVisible(false);
        }
        if (SafeNoteActionEnum.EDIT.equals(safeNoteAction))
        {
        	optionMenu.getItem(Constants.SAFE_NOTE_EDIT_MENU_ITEM_INDEX).setVisible(false);
        }
        if (SafeNoteActionEnum.VIEW.equals(safeNoteAction))
        {
        	optionMenu.getItem(Constants.SAFE_NOTE_SAVE_MENU_ITEM_INDEX).setVisible(false);
        }
		return true;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) 
	{
		switch (item.getItemId()) 
		{
			case R.id.addSafenoteBackMenuItem:
				back2NoteList();
				break;
			case R.id.addSafenoteEditMenuItem:
				safeNoteAction = SafeNoteActionEnum.EDIT;
				setControlsEnabling(true);
				optionMenu.getItem(Constants.SAFE_NOTE_EDIT_MENU_ITEM_INDEX).setVisible(false);
				optionMenu.getItem(Constants.SAFE_NOTE_SAVE_MENU_ITEM_INDEX).setVisible(true);
				break;	
			case R.id.addSafenoteSaveMenuItem:
				saveSafeNote();
				break;
			case R.id.addSafenoteDeleteMenuItem:
				deleteConfirmationDialog();
				break;	
			default:
				super.onMenuItemSelected(featureId, item);
				break;
		}
		return true;
	}

	private void setControlsEnabling(boolean isEnable) 
	{
		// set visibility of safe note name edit text
		editTextName.setEnabled(isEnable);
		editTextName.setFocusable(isEnable);
		editTextName.setFocusableInTouchMode(isEnable);
		
		// set visibility of safe note category edit text
		editTextCategory.setEnabled(isEnable);
		editTextCategory.setFocusableInTouchMode(isEnable);
		
		// set visibility of safe note body edit text
		editTextBody.setEnabled(isEnable);
		editTextBody.setFocusableInTouchMode(isEnable);
	}

	private void initControls()
    {
    	textViewID = (TextView) findViewById(R.id.safenote_textview_id);
    	editTextName = (EditText) findViewById(R.id.safenote_edittext_name);
        editTextCategory = (AutoCompleteTextView) findViewById(R.id.safenote_edittext_category);
        autoCompleteTextViewAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, categoryList);
        editTextCategory.setAdapter(autoCompleteTextViewAdapter);
        editTextBody = (EditText) findViewById(R.id.safenote_edittext_body);
    }
    
    private void populateSafeNoteValues() 
    {
    	textViewID.setText(safeNote.getSafeNoteID());
    	editTextName.setText(safeNote.getSafeNoteName());
    	editTextCategory.setText(safeNote.getSafeNoteCategoryName());
    	editTextBody.setText(decryptBodyText(safeNote.getSafeNoteBody()));
	}
    
	private void deleteSafeNote() 
	{
		try
		{
	    	clientResource = new ClientResource(Constants.APP_ENGINE_SERVER_URL + "/delete/" + safeNote.getSafeNoteID());
	    	safeNoteResource = clientResource.wrap(SafeNoteResource.class);
	    	safeNoteResource.remove(safeNote.getSafeNoteID());
		}
		catch (ResourceException re)
		{
			re.printStackTrace();
		}
		finally
		{
			postSafeNoteAction(SafeNoteActionEnum.DELETE, getString(R.string.string_the_safe_note_is_deleted_successfully));
			finish();
		}
		
	}
    
	private void postSafeNoteAction(SafeNoteActionEnum safeNoteAction, String message) 
	{
		Bundle bundle = new Bundle();
		bundle.putSerializable(Constants.KEY_SAFE_NOTE, safeNote);
		bundle.putSerializable(Constants.KEY_ACTION, safeNoteAction);
		bundle.putString(Constants.KEY_MESSAGE, message);
		Intent returnIntent = new Intent();
		returnIntent.putExtras(bundle);
		setResult(RESULT_OK,returnIntent); 
	}

	private void saveSafeNote() 
	{
		String encryptedBody = encryptBodyText();
		if (encryptedBody == null)
		{
			return;
		}
		safeNote.setSafeNoteOwner("vogash@gmail.com");
		safeNote.setSafeNoteID(String.valueOf(textViewID.getText()));
		safeNote.setSafeNoteIcon("google.png");
		safeNote.setSafeNoteName(editTextName.getText().toString());
		safeNote.setSafeNoteCategoryName(editTextCategory.getText().toString());
		safeNote.setSafeNoteBody(encryptedBody);
		try
		{
	        clientResource = new ClientResource(Constants.APP_ENGINE_SERVER_URL);
			safeNoteResource = clientResource.wrap(SafeNoteResource.class);
			safeNoteResource.store(safeNote);
		}
		catch (ResourceException re)
		{
			re.printStackTrace();
		}
		finally
		{
			String message;
			if (SafeNoteActionEnum.ADD.equals(safeNoteAction))
			{
				message = getString(R.string.string_the_safe_note_is_added_successfully);
			}
			else
			{
				message = getString(R.string.string_the_safe_note_is_updated_successfully);
			}
			postSafeNoteAction(safeNoteAction, message);
			finish();
		}
	}
	
	public void deleteConfirmationDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.string_are_you_sure_you_want_to_delete)
		       .setCancelable(false)
		       .setPositiveButton(R.string.string_yes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   deleteSafeNote();
		           }
		       })
		       .setNegativeButton(R.string.string_no, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void back2NoteList() 
	{
		finish();
	}
	
	private String encryptBodyText()
	{
		String encryptedText;
		try
		{
			encryptedText = editTextBody.getText().toString();
			encryptedText = cipher.encrypt(editTextBody.getText().toString());
		}
		
		catch (Exception e)
		{
			MessageBox("Error", "Enabled to encrypt the safe note", "Close" );
			return null;
		}
		return encryptedText;
	}
	
	private String decryptBodyText(String bodyText)
	{
		String decryptedText = "";
		try
		{
			decryptedText = cipher.decrypt(bodyText);
		}
		
		catch (Exception e)
		{
			MessageBox("Error", "Enabled to decrypt the safe note", "Close" );
			return bodyText;
		}
		return decryptedText;
	}
	
    public void MessageBox(String title, String message, String buttonText )
	{
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(message)
		.setPositiveButton(buttonText,new DialogInterface.OnClickListener() 
		{    
		    public void onClick(DialogInterface dialog, int which) 
		    {                        
		    }
		}).show();
	}
}
